package com.ywb.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ywb.entity.EduSubject;
import com.ywb.entity.excel.SubjectData;
import com.ywb.service.EduSubjectService;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    //因为Listener需要我们手动处理数据所以不能交给Spring进行管理,无法使用AutoWired进行装配
    //为了实现数据库操作我们需要添加有参构造并调入Service
    public EduSubjectService subjectService;
    public SubjectExcelListener(EduSubjectService subjectService){
        this.subjectService = subjectService;
    }
    public SubjectExcelListener(){}

    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if(subjectData == null){
            throw new MyException(20001, "文件数据为空");
        }
        //处理每行的第一个值的一级分类和第二个值二级分类
        EduSubject existFirstSubject = this.existFirstSubject(subjectService, subjectData.getFirstSubjectName());
        if(existFirstSubject == null){ //没有该一级分类,进行添加
            //直接创建出一个EduSubject
            existFirstSubject = new EduSubject();
            //一级分类的parentId为0, title从读的数据中取一级分类的名字
            existFirstSubject.setParentId("0");
            existFirstSubject.setTitle(subjectData.getFirstSubjectName());
            subjectService.save(existFirstSubject);
        }
        EduSubject existSecondSubject = this.existSecondSubject(subjectService, subjectData.getSecondSubjectName(), existFirstSubject.getId());
        if(existSecondSubject == null){
            //直接创建出一个EduSubject
            existSecondSubject = new EduSubject();
            //一级分类的parentId为0, title从读的数据中取一级分类的名字
            existSecondSubject.setParentId(existFirstSubject.getId());
            existSecondSubject.setTitle(subjectData.getSecondSubjectName());
            subjectService.save(existSecondSubject);
        }

    }

    //判断一二级分类是否存在,避免重复增加
    private EduSubject existFirstSubject(EduSubjectService subjectService, String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", "0");
        EduSubject firstSubject = subjectService.getOne(wrapper);
        return firstSubject;
    }

    private EduSubject existSecondSubject(EduSubjectService subjectService, String name, String pId){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();
        wrapper.eq("title", name);
        wrapper.eq("parent_id", pId );
        EduSubject secondSubject = subjectService.getOne(wrapper);
        return secondSubject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
